<template>
  <!-- 待收费 -->
  <workStatistics :todayData="today"></workStatistics>
  <zsearch  v-loading="loading">
      <template #title>
        <span>待收费</span>
      </template>
      <template #date>
        <el-date-picker
            class="date-1"
            type="date"
            v-model="date"
            @change="handleChangeDate"
            placeholder="选择日期">
        </el-date-picker>
      </template>
      <template #select>
        <el-input class="input-1" v-model="name" placeholder="患者/电话/病历号"></el-input>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch">查询</el-button>
	      <el-button class="btn-2">导出</el-button>
      </template>
      <template #table>
        <ztable
          :height="'100%'"
          :tableData='data' 
          :strucs='columns'
          :width="'200'"
          :isshowOperation="true"
          @onToDetail="onToDetail"
        >
        <template #default="slotScope">
          <el-button type="text" class="operation" v-jurisdiction="'pay:order:collection:list'" @click="goChargeHistory(slotScope.rowData)" >收费历史</el-button>
          <el-button type="text" class="operation" v-jurisdiction="'customer:order:pay'" @click="goCharge(slotScope.rowData)">收费</el-button>
          <!-- <el-button type="text" class="operation" @click="handleGrant(slotScope.rowData, slotScope.index)">发券</el-button> -->
          <el-button 
                type="text"
                class="operation" 
                @click="handleDelItem(slotScope.rowData)"
                v-jurisdiction="'customer:order:new:del'"
                >删除</el-button>
        </template>
        </ztable>
        
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total"
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>

  <zdialog title="发放优惠券" @handleClose="closeDialog" v-model="dialogVisible" :btnData="dialogBtnData">
    <template #body>
      <div class="flex-wrap">
        <div class="leftToRight-layout">
          <div class="label" style="width: 90px">
            <span>优惠券模板</span>
          </div>
          <div class="operations">
            <el-select v-model="modelId"  placeholder="请选择">
              <el-option
                v-for="item in modelOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="leftToRight-layout">
          <div class="label">
            <span>数量</span>
          </div>
          <div class="operations">
            <el-input-number v-model="count" :min="1" :max="10" ></el-input-number>
          </div>
        </div>
      </div>
      
    </template>
  </zdialog>

  <zdialog :title="arrearsTitle" :width="'45%'" @handleClose="closeDialog" v-model="dialogVisibleCharge" :btnData="dialogChargeBtn">
    <template #body>
        <header class="flex">
          <div class="person-info">
            <div class="avarat">
              <el-avatar v-if="customerSex === '男'" size="small" :src="male"></el-avatar>
              <el-avatar v-if=" customerSex === '女'" size="small" :src="female"></el-avatar>
            </div>
            <span class="name">{{customerName || 'hh'}}</span>
          </div>
          <div class="info">
            <div>
              <span class="infos-label">病历号：</span>
              <span>{{customerHistorySickNum || '暂无'}}</span>
            </div>
            <div>
              <span class="infos-label">手机：</span>
              <span>{{customerPhone || '暂无'}}</span>
            </div>
          </div>
          <!-- <div class="info">
            <div>
              <span class="infos-label">就诊类型: </span>
              <span>11111111</span>
            </div>
            <div>
              <span class="infos-label">预约项目: </span>
              <span>11111111</span>
            </div>
          </div> -->
        </header>
        <div class="dialog-content">
          <!-- 项目 -->
          <div class="project" v-if="arrearsTitle === '收费'">
            <el-table
                :data="addProjectList"
                style="width: 100%"
                :header-cell-style="{background:'#fff', color:'#000'}"
                >
                <el-table-column
                  v-for="(item) in MockColumns"
                  :key="item.name"
                  :prop="item.name"
                  :label="item.lable"
                  :width="item.name === 'toothBit' ? '120' : ''"
                  align="center"
                  >
                  <template #default="scope">
                    <div v-if="item.name === 'toothBit'" >
                      <div style="">
                        <ztooth 
                          :lTToolist="scope.row[item.name].leftTop" 
                          :rTToolist="scope.row[item.name].rightTop" 
                          :lBToolist="scope.row[item.name].leftBottom" 
                          :rBToolist="scope.row[item.name].rightBottom"
                          @getLeftData="(() => getLeftData(scope.$index))()"
                          @getRightData="(() => getRightData(scope.$index))()"
                          @getLeftBottomData="(() => getLeftBottomData(scope.$index))()"
                          @getRightBottomData="(() =>getRightBottomData(scope.$index))()"
                          ></ztooth>
                      </div>
                    </div>
                    <!-- <template v-else-if="item.name === 'priceShow'">
                      <el-input v-model="scope.row[item.name]" @change="handleChange"  class="mini-btn"></el-input>
                    </template>
                    <template v-else-if="item.name === 'number'">
                      <el-input v-model="scope.row[item.name]" @change="handleChange" class="mini-btn"></el-input>
                    </template>
                    <template v-else-if="item.name === 'money'">
                      <el-input v-model="scope.row[item.name]"  class="mini-btn"></el-input>
                    </template> -->
                    <template v-else-if="item.name === 'doctorId'">
                      {{getName(optionsDoctors, scope.row[item.name])}}
                      <!-- <el-select class="select-4" v-model="scope.row[item.name]" filterable placeholder="请选择">
                        <el-option
                          v-for="item in optionsDoctors"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select> -->
                    </template>
                    <template v-else-if="item.name === 'nurseId'">
                      {{getName(optionsNurse, scope.row[item.name])}}
                      <!-- <el-select class="select-4" v-model="scope.row[item.name]" filterable placeholder="请选择">
                        <el-option
                          v-for="item in optionsNurse"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select> -->
                    </template>
                    <template v-else-if="item.name === 'consultantId'">
                      {{getName(secondaryUserOptions, scope.row[item.name])}}
                      <!-- <el-select class="select-4" 
                        v-model="scope.row[item.name]" 
                        filterable
                        placeholder="请选择"
                        >
                        <el-option
                          v-for="item in secondaryUserOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                        </el-option>
                      </el-select> -->
                    </template>
                    <div v-else>{{scope.row[item.name]}}</div>
                  </template>
                </el-table-column>
                  <!-- <el-table-column fixed="right" label="操作" width="100">
                    <template #default="scope">
                      <el-button
                        @click="del(scope.row, scope.$index)"
                        type="text"
                        size="small"
                        class="btn-text"
                      ><i class="el-icon-delete-solid"></i></el-button>
                      </template>
                  </el-table-column> -->
            </el-table>
            <div class="charge-r-total">
              <span>总计金额: {{ orderDetailSumMoneyShow || '00.00'}}</span>
              <span>应付金额: {{ originalPriceShow || '00.00'}}</span>
              <!-- <span>
                <span>实付金额: </span>
                <el-input class="input-5" @change="handleChangeValue" v-model="paidInAMountInput"></el-input>
              </span> -->
            </div>
            <!-- 支付方式 -->
          <div class="Payment-method">
            <div class="advance">
              <!-- <div class="advance-head" >
                <div class="head-title">
                  <span class="total">预付款: </span>
                  <span>0.0</span>
                  <span>积分: 0</span>
                  <span>(抵现: 0.0)</span>
                </div>
                <div class="head-btn">
                  <i class="el-icon-edit"></i>
                  <i class="el-icon-sort"></i>
                </div>
              </div> -->
              <div class="advance-content">
                  <div class="group" v-for="(item, index) in payment" :key="index">
                    <div class="group-left">
                      <div class="label">支付方式: </div>
                      <el-select class="select-3 machin-select" v-model="item.payType"  placeholder="请选择">
                        <el-option
                          v-for="item in paymentOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                          :disabled="item.disabled"
                          >
                        </el-option>
                      </el-select>
                      <div class="label">实付金额: </div>
                      <el-input class="input-5" v-model="item.moneyShow" >
                          <template #prepend>￥</template>
                        </el-input>
                    </div>
                    <div class="group-right">
                      <el-icon v-if="item.isAdd" @click="addPayment"><plus /></el-icon>
                      <el-icon v-else @click="delPayment(index)"><minus /></el-icon>
                      
                    </div>
                  </div>
              </div>
            </div>
          </div>

          </div>
          <!-- 历史欠费 -->
          <div class="history-project">
            <div class="arrears-content">
                <el-table
                    :data="arrearsData"
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    default-expand-all
                    >
                      <el-table-column
                        type="selection"
                        width="55">
                      </el-table-column>
                      <el-table-column type="expand">
                        <template #default="props">
                          <!-- 支付方式 -->
                          <div class="Payment-method">
                            <div class="advance" style="border: 0">
                              <div class="advance-content" >
                                  <div class="group" v-for="(item, index) in props.row.payment">
                                    <div class="group-left">
                                      <div class="label">支付方式: </div>
                                      <el-select class="select-3 machin-select" v-model="item.payType"  placeholder="请选择">
                                        <el-option
                                          v-for="item in paymentOptions"
                                          :key="item.id"
                                          :label="item.name"
                                          :value="item.id"
                                          :disabled="item.disabled"
                                          >
                                        </el-option>
                                      </el-select>
                                      <div class="label">实付金额: </div>
                                      <el-input class="input-5" 
                                        v-model="item.moneyShow" 
                                        @change="handleChangeInputVal($event, props.row)"
                                      >
                                          <template #prepend>￥</template>
                                        </el-input>
                                    </div>
                                    <div class="group-right">
                                      <el-icon v-if="item.isAdd" @click="addPaymentItemList(props.row.payment)"><plus /></el-icon>
                                      <el-icon v-else @click="delPaymentItemList(props.row.payment, index)"><minus /></el-icon>
                                      
                                    </div>
                                  </div>
                              </div>
                            </div>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column 
                        show-overflow-tooltip
                        v-for="(item) in arrearsColumns"
                          :key="item.name"
                          :prop="item.name"
                          :label="item.viewName"
                          :width="item.columnWidth ? item.columnWidth : 'auto'"
                          align="center"
                      >
                            <template #default="scope">
                              <div>{{scope.row[item.name]}}</div>
                            </template>
                        </el-table-column>
                  </el-table>
            </div>
            <header class="arrears-head">
              <span class="total">总欠费: </span>
              <span>{{totalArrears()}}</span>
            </header>
          </div>
          
          <!-- 备注 -->
          <div class="info-footer">
            <div class="owe">
              <header class="owe-head">
                <div class="head-l">
                  <span>欠费: </span>
                  <span>{{allArrearsCopy || 0}}</span>
                </div>
                <div class="head-r">
                  <span>馈赠金: </span>
                  <span>{{giftsOfGoldShow || 0}}</span>
                </div>
                <div class="head-r">
                  <span>账户余额: </span>
                  <span>{{accountBalance || 0}}</span>
                </div>
                <div class="head-r">
                  <span>实付总额: </span>
                  <span>{{paid() + paidArrearageList}}</span>
                </div>
                <span></span>
              </header>
              <!-- 先隐藏 -->
              <el-row align="middle" v-show="arrearsTitle === '收费'">
                <el-col :span="3" style="padding-left: 20px">付款时间</el-col>
                <el-col :span="8">
                  <el-date-picker
                    v-model="payTime"
                    type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择时间"
                  />
                </el-col>
              </el-row>
              <div class="owe-conntent">
                  <span>备注</span>
                  <el-input type="textarea" class="input-1" v-model="remark"></el-input>
              </div>
            </div>
          </div>
          
        </div>
      
    </template>
  </zdialog>
  <!-- 打印 -->
  <printHtml class="none" id="print-js" :printList='printList'></printHtml>
</template>

<script lang='ts'>
import { Plus, Minus} from '@element-plus/icons-vue'
import { defineComponent, reactive, toRefs, ref, computed, watch, onMounted, nextTick } from '@vue/runtime-core'

import useRequet, { RespData } from "../../hook/network"
import usePromiseRequest from "../../hook/request"
import {OptionDisable, Doctors, MockType, ArrearsOrderPay, WsMessageType} from "../../types"
import { getName } from "../../usefn/getName"
import { debounce } from "../../utils/debounce"


import {  getOrderInfoAndDetailApi } from '../../api/refund'

import useConfgin from '../../hook/getconfig'

import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import ztooth from "../../components/tooch/imgTooth.vue"

import workStatistics from "../../components/workStatistics/work.vue"

import { getDoctorListAllAPi, getNurseListAllAPi, getConsultListAllAPi, getCustomerAccountApi } from "../../api/common"

import { getNowDate } from "../../utils/nowDate"
import { delOrderApi } from '../../api/order';

import zdialog from '@components/dialog/dialog.vue'
import zarrears from "../patients/details/chargeModel/arrears.vue"
import {TemOption} from "../../types"
// 详情添加患者
import useSetAddLog from "../../hook/setAddLog"
import {useRouter} from "vue-router"

import { ElMessage, ElMessageBox } from 'element-plus'
// 引入图片资源
import male from "../../assets/image/male-adult.png"
import female from "../../assets/image/female-adult.png"
import arrearsVue from '../patients/details/chargeModel/arrears.vue'
import printHtml from '@components/printHtml/printHtml.vue'
import printJS from 'print-js'

type PayMoneys = {
  orderId: number,
  details: Details[]
}
type Details = {
  isAdd: boolean,
  payType: string,
  moneyShow: string | number
}
const configID = 528
export default defineComponent({
  name: 'WaitingCharge',
  components: {
    ztable,
    zpage,
    zsearch,
    ztooth,

    zdialog,
    zarrears,
    printHtml,

    workStatistics,
    Plus, Minus
  },
  setup() {
    const router = useRouter()
    let search = reactive({
      date: getNowDate(),
      name:'',
      current: 1,
      size: 10,
      total: 0,
      
      loading: false
    })
    let today = reactive({
      todayNewCustomer: 0,
      todayNewSub: 0,
      todayNewCollection: 0,
      todayNewAccessLog: 0,
      todayNewSickMedicalRecords: 0
    })

    let person = reactive({
      customerName: '',
      customerSex: '',
      customerHistorySickNum: '',
      customerPhone: '',

    })
    const data = ref([])
    // 待收费
    const rowsList = useConfgin(configID)
    const columns = rowsList.groupDataList.value;
    
    

    //发券
    const handleGrant = (RowData: any, index: number) => {
      id.value = RowData.id
      getmodelOptions()
      dialogVisible.value = true
    }

    const request = useRequet({ path: "" });

    const tableHeight = computed(()=> 100% - 60)

    const req = () => {
      search.loading = true
      let params = {
        day:search.date,
        current: search.current,
        size: search.size,
        customerQueryValue: search.name
      }
      request.sendRequest({
        address: '/pay/order/toChargeList',
        params,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
					data.value = resp.data.records
          search.total = resp.data.total
          search.current = resp.data.current
          data.value.map((item:any,index) => {
            item.index = ++index
          })

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          search.loading = false
        },
        method: "POST",
      })
    }
    req()
    const getTodayStatistics = () => {
      request.sendRequest({
        address: '/pay/order/todayStatistics',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          today.todayNewCustomer = resp.data.todayNewCustomer
          today.todayNewSub = resp.data.todayNewSub
          today.todayNewCollection = resp.data.todayNewCollection
          today.todayNewAccessLog = resp.data.todayNewAccessLog
          today.todayNewSickMedicalRecords = resp.data.todayNewSickMedicalRecords

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取失败')
          
        },
        method: "POST",
      })
    }
    getTodayStatistics()

    const debounceRefresh = debounce(req, 1000)
    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }

    const handleChangeDate = (d: Date) => {
      search.date = getNowDate(d)
    }

    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
		}

    // 去详情
    const onToDetail = (id: number) => {
      useSetAddLog(id)
      router.push(`/allPatientDetails/${id}/patient`)
    }

    const dialogVisible = ref(false)
    const modelOptions = ref([] as TemOption[])
    const modelId = ref('')
    const id = ref('')
    const count = ref(1)
    const closeDialog = () => {
      dialogVisible.value = false
      dialogVisibleCharge.value = false
    }
    const dialogBtnData = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisible.value = false
				}
      },
      {
        name: '保存',
        func: (data:object) => {
					console.debug('保存',JSON.parse(JSON.stringify(data)))
          if(id && modelId.value && count.value) {
            request.sendRequest({
              address: 'pay/coupons/getIssueCouponsModel',
              params: {
                customerId: id.value,
                modelId: modelId.value,
                count: count.value
              },
              success: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
                ElMessage.success('发送优惠券'+ resp.msg)
                closeDialog()
              },
              fail: (resp: RespData) => {
                if(resp.code !== 0) return ElMessage.error(resp.msg)
                
              },
              method: "GET",
            })
          } else {
            ElMessage.warning('请选择必要参数')
          }
          
				}
      }
    ]
    const getmodelOptions = () => {
      request.sendRequest({
        address: 'pay/coupons/getIssueCouponsModel',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          modelOptions.value = resp.data
          
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }

    // 删除划价单
    const handleDelItem = (rowData: any) => {
      let id = rowData.id
      ElMessageBox.confirm('此操作将永久删除该订单， 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
				let res:any = await delOrderApi({}, rowData.id)
        if(res.code !== 0) return ElMessage.error('操作' + res.msg)
        ElMessage.success('删除成功');
        req()
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })
    }


    // 去收费历史
    const goChargeHistory = (rowData: any) => {
      let id = rowData.customerId
      router.push({path:`/allPatientDetails/${id}/chargeModel`, query: {type: 4}})
      
    }

    let personInfo = reactive({
      customerId: '',
      customerName: '',
      customerSex: '',
      customerPhone: '',
      customerHistorySickNum: '',
    })

    const getOrderDetails = async(id: number) => {
      let result:any = await getOrderInfoAndDetailApi({}, id)
      if(result.data != null) {
        let order = result.data.details
        order.forEach((i: { toothBit: string }) => {
          i.toothBit = JSON.parse(i.toothBit)
        })
        addProjectList.value = order
        orderDetailSumMoneyShow.value = result.data.orderDetailSumMoneyShow
        originalPriceShow.value = result.data.originalPriceShow

        setPamentMoney(originalPriceShow.value)
        
      }
    }

    // 重新获取账户余额
    const getCustomerAccount = async(id:number) => {
      let res:any = await getCustomerAccountApi({}, id);
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')

      let num = res.data.giftsOfGoldShow || 0;
      let balance = res.data.balanceShow || 0;
      window.localStorage.setItem('balanceShow', balance)
      window.localStorage.setItem('giftsOfGoldShow', num)

      accountBalance.value = balance;
      giftsOfGoldShow.value = num;

    }
    const isOrderOut = ref(true)
     // 收费
    const goCharge = async(rowData: any) => {
      if(rowData.status === '待付款') {
        isOrderOut.value = false
      }
      console.log(rowData)
      let {id, customerId, customerName, customerSex, customerPhone, customerHistorySickNum, arrears} = rowData;
      getCustomerAccount(customerId)
      await getOrderDetails(id)
      await getCustomerDebtOrder(customerId)
      personInfo.customerId = customerId
      personInfo.customerName = customerName;
      personInfo.customerSex = customerSex;
      personInfo.customerPhone = customerPhone;
      personInfo.customerHistorySickNum = customerHistorySickNum;
      newOrderId.value = id

      createTime.value = rowData.createTime

      allArrearsCopy.value = totalArrears()

      arrearsTitle.value = '收费'
      dialogVisibleCharge.value = true

      
      
      getPayMent()
      getDoctorAndNurse()
    }

    const list  = reactive({
      // 收欠费数据
      arrearsData: <any>[],
      arrearsColumns:[
        {
           id: 529,
            name: "createTime",
            viewName: "创建时间",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'120',
        },
        {
           id: 529,
            name: "masterUserName",
            viewName: "医生",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "originalPriceShow",
            viewName: "应收",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "amountMoneyShow",
            viewName: "实收",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "arrears",
            viewName: "欠款",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        },
        {
           id: 529,
            name: "remark",
            viewName: "备注",
            type: 208,
            groupId: 501,
            dataSource: "",
            hint: null,
            defaultValue: null,
            length: null,
            minValue: null,
            maxValue: null,
            rangx: null,
            must: 1,
            errorHit: "",
            value: "",
            orderNum: 1,
            show: 1,
            canUpdate: 0,
            companyId: 1,
            listView: 1,
            insertShow: 1,
            canShow: 1,
            fixed: null,
            idName: null,
            columnWidth:'',
        }
      ],
      // 支付方式
      payment:[
        {
          isAdd: true, // 是否显示添加
          payType: '微信', // 支付方式
          moneyShow: '' // 实付金额
        }
      ],
      arrearsList: <PayMoneys[]>[],

      remark:'',
      loading: false,
      payMoneys: <PayMoneys[]>[

      ]
    })


    // 设置第一个支付方式 初始金额金额
    const setPamentMoney = (money: any) => {
      list.payment[0].moneyShow = money
    }

    const createTime =  ref('')
    const payTime = ref(getNowDate())

    // 收费相关
    const arrearsTitle = ref('收费')
    const dialogVisibleCharge = ref(false)
    const dialogChargeBtn = [
      {
        name: '取消',
				func: (data:object) => {
					console.debug('取消',JSON.parse(JSON.stringify(data)))
          dialogVisibleCharge.value = false
				}
      },
      {
        name: '确定',
				func: async(data:object) => {
					console.debug('确定',JSON.parse(JSON.stringify(data)))
          if(arrearsTitle.value === '收费') {
            let res = list.payment.every(i => i.payType)
            if(res) {
              if(isOrderOut.value) {
                console.log('tr进来')
                
                await saveOrder()
                handleArrears()
              } else {
                
                // list.payMoneys = []
                list.payMoneys.push({
                  orderId: newOrderId.value,
                  details: list.payment
                })

                // 收费接口
                handleArrears()
              }
              
              
            } else {
              ElMessage.warning('请选择支付方式')
              return false
            }
          }
				}
      },
    ]

    // 展示项目
    // 新增表格结构
    const MockColumns = [
      {
        name: 'toothBit',
        lable: '牙位'
      },
      {
        name: 'itemName',
        lable: '项目名称'
      },
      // {
      //   name: 'projectCode',
      //   lable: '项目编码'
      // },
      {
        name: 'unit',
        lable: '单位'
      },
      {
        name: 'priceShow',
        lable: '单价'
      },
      {
        name: 'realPriceShow',
        lable: '金额'
      },
      {
        name: 'number',
        lable: '数量'
      },
      {
        name: 'doctorId',
        lable: '医生'
      },
      {
        name: 'nurseId',
        lable: '护士'
      },
      {
        name: 'consultantId',
        lable: '咨询师'
      },
    ]
    // 项目
    const addProjectList = ref<any[]>([])
    const getLeftData = (index: number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.leftTop = data
      }
    }
    const getRightData = (index:number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.rightTop = data
      }
    }

    const getLeftBottomData = (index:number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.leftBottom = data
      }
    }

    const getRightBottomData = (index: number) => {
      return (data: MockType[]) => {
        addProjectList.value[index].toothBit.rightBottom = data
      }
    }

     // 订单原价 
    const orderDetailSumMoneyShow = ref('')
    // 实际应付款（折后价）
    const originalPriceShow = ref(0)

    // 账户余额
    const accountBalance = ref(0)
    const giftsOfGoldShow = ref(0)
    
    // 总欠费
    const totalArrears = () => {
      let total = 0
      list.arrearsData.forEach((item: any) => {
        // 欠费 = 应收 - 实收
        total += item.arrears
      })
      return total
    }
    // （总账单的）实付金额
    const paid = () => {
      let money = 0
      list.payment.forEach(item => {
        money += Number(item.moneyShow)
      })
      return money
    }

     // 侦听收欠费
    const paidArrearageList = computed(() => {
      let money = 0
      list.payMoneys.forEach(item => {
        item.details.map(j => {
          money += Number(j.moneyShow)
        })
        
      })

      return money
    })

    // （该项目的）实付金额
    const paidInAmount = computed(() => {
      let money = 0
      // （总账单的）实付金额 =  实际应付款
      if(paid() === originalPriceShow.value) {
        money = paid()
      }
      // （总账单的）实付金额 < 实际应付款
      if(paid() <= originalPriceShow.value) {
        money = paid()
      } else {
        // （总账单的）实付金额 > 实际应付款
        // 钱够了 
        money = originalPriceShow.value
      }


      
      return money
    })
    // 实付金额输入
    const paidInAMountInput = ref(0)
    // 余下的钱
    const restMoney = ref(0)
    // 所有欠费
    let allArrearsCopy = ref(0)
    watch(paid, (newP, prevP) => {
      if(arrearsTitle.value === '收费') {
        if(newP <= originalPriceShow.value) {
          paidInAMountInput.value = newP
          list.arrearsData.forEach((i:any) => i.paymentAmount = '')
        } else {
          // 这里是大于 项目实付金额
          paidInAMountInput.value = originalPriceShow.value;
          // 余下的钱 = 实付总额 - 实付金额（项目）
          restMoney.value = newP - originalPriceShow.value;

          for(let i = 0; i < list.arrearsData.length; i++) {
            // let restM = restMoney.value;
            if(restMoney.value - list.arrearsData[i].arrears >= 0) {
              // 说明 还有钱
              restMoney.value = restMoney.value - list.arrearsData[i].arrears
              
              // 
              if(restMoney.value >= 0) {
                list.arrearsData[i].paymentAmount = list.arrearsData[i].arrears
                
              } else {
                list.arrearsData[i].paymentAmount = restMoney.value
              }
              
            } else if (restMoney.value - list.arrearsData[i].arrears === 0) {
              list.arrearsData[i].paymentAmount = restMoney.value
              return false
            } else {
              // 钱不够
              list.arrearsData[i].paymentAmount = restMoney.value
              return false
            }
          }

        }
      }

      if(arrearsTitle.value === '收欠费') {
        
        
      }

      // if(newP > allArrearsCopy.value) {
      //   ElMessage.warning('注意：您输入的实付金额, 已经超出欠费金额！')
      // }


    } )

    // 订单核算
    const handleAccountingOrder = () => {
      let params = {
        customerId: Number(id),
        masterUserId: '',
        secondaryUserId: '',
        useCouponsIds: [],
        details: addProjectList.value,
        createTime: createTime.value
      }
      request.sendRequest({
        address: 'pay/order/accountingOrder',
        params,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取信息失败')
          originalPriceShow.value = resp.data.originalPriceShow
          orderDetailSumMoneyShow.value = resp.data.orderDetailSumMoneyShow
          addProjectList.value = resp.data.details

          setPamentMoney(originalPriceShow.value)

        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }

    const handleChange = () => {
      handleAccountingOrder()
    }

    // 验证输入框金额不大于实付金额 （提示）
    const handleVolidateFn = (arrears: number) => {
      // let total = paid.value;
      // let paidIn = originalPriceShow.value
      let result = 0;
      list.payMoneys.forEach((i) => {
        console.log(i.details)
        i.details.forEach(j => {
          result += Number(j.moneyShow)
        })
      })
      if(result > arrears) {
        ElMessage.error('请注意：您输入的金额大于欠费总额')
        return false
      }
    }
    // 欠费历史输入实付
    const handleChangeInputVal = (val: string, data: any) => {
      let arrears = data.arrears || 0;
      let res = Number(val)
      
      // res > arrears ? ElMessage.error('请注意：您输入的金额大于欠费总额') : null;
      // handleVolidateFn(arrears)
    }
    

    const handleChangeValue = () => {
      
    }

    // 医生下拉数据
    const optionsDoctors = ref([] as Doctors[])
    const optionsNurse = ref([] as Doctors[])
    const secondaryUserOptions = ref([] as Doctors[])
    const getDoctorAndNurse = async() => {
      // 获取医生
      let res:any = await getDoctorListAllAPi({})
      if(res.code !== 0) return ElMessage.error(res.msg || '获取信息失败')
      optionsDoctors.value = res.data

      // 获取护士
      let res1:any = await getNurseListAllAPi({})
      if(res1.code !== 0) return ElMessage.error(res1.msg || '获取信息失败')
      optionsNurse.value = res1.data
      

      // 获取咨询师
      let res2:any = await getConsultListAllAPi({})
      if(res2.code !== 0) return ElMessage.error(res2.msg || '获取信息失败')
      secondaryUserOptions.value = res2.data
      
    }
    

    const del = (data: any, index: number) => {
      addProjectList.value.splice(index, 1)
      handleAccountingOrder()
    }
    // 支付方式
    const paymentOptions = ref([] as OptionDisable[])
    const disabledOption = (arr: Details[]) => {
      let newArr = arr.map(i => i.payType)
      paymentOptions.value.forEach((i, index) => {
        if(i.id === newArr[index]) {
          i.disabled = true
        }
      })
    }
    const addPayment = () => {
      disabledOption(list.payment)
      let res = list.payment.every(i => i.payType)
      console.log(res)
      if(res) {
        list.payment.push({
          isAdd: false,
          payType: '',
          moneyShow: '',
        })
      } else {
        ElMessage.warning('请选择支付方式')
      }
      
    }
    const delPayment = (index: number) => {
      let payType = list.payment[index].payType
      let refreshDisable = paymentOptions.value.find(i => i.id === payType)
      if(refreshDisable) {
        refreshDisable.disabled = false
      }
      list.payment.splice(index, 1)
    }

    const addPaymentItemList = (item: Details[]) => {
      disabledOption(item)
      console.log(item, '添加一项')
      let res = item.every(i => i.payType)
      if(res) {
        item.push({
          isAdd: false, // 是否显示添加
          payType: '', // 支付方式
          moneyShow: '' // 实付金额
        })
      } else {
        ElMessage.warning('请选择支付方式')
      }
      
    }
    const delPaymentItemList = (item: Details[], index:number | symbol| string) => {
      let payType = item[index].payType
      let refreshDisable = paymentOptions.value.find(i => i.id === payType)
      if(refreshDisable) {
        refreshDisable.disabled = false
      }
      console.log(index, '删除的索引')
      item.splice(Number(index), 1)
    }
    // 获取患者欠费订单
    const getCustomerDebtOrder = async(ID: number) => {
      list.loading = true
      list.arrearsData = []
      let result:any = await usePromiseRequest(`pay/order/getCustomerDebtOrder/${ID}`, {}, 'GET')
      if(result.code !== 0) return ElMessage.error(result.msg)
      list.arrearsData = result.data || []
      list.arrearsData.forEach((item: any) => {
            item.payment = [
                {
                  isAdd: true, // 是否显示添加
                  payType: '', // 支付方式
                  moneyShow: '' // 实付金额
                }
            ]
          })
      list.loading = false
      
    }
    
    const getPayMent = () => {
      request.sendRequest({
        address: 'pay/order/getCustomerType',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          paymentOptions.value = resp.data
          paymentOptions.value.forEach(i => i.disabled = false)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "GET",
      })
    }
    

    const handleSelectionChange = (data: any) => {
      console.log(data, '勾选的数据')
      let arr = <PayMoneys[]>[]
      data.forEach((item: any) => {
        arr.push({
          orderId: item.id,
          details: item.payment
        })
      })
      
      list.payMoneys.push(...arr)
      console.log('勾选的数据', list.payMoneys)
      // list.payMoneys = arr
    }
    const newOrderId = ref()

     // 新建账单保存(下单未付款)
    const saveOrder = async() => {
      if(addProjectList.value.length <= 0) {
        ElMessage.warning('您还未选择项目')
        return false
      } else {
        type OrderParams = {
          id?: number | null,
          customerId: number | string,
          details: any[],
          createTime: string,
          originalPriceShow: number
        }
        let params:OrderParams = {
          customerId: personInfo.customerId,
          details: addProjectList.value,
          createTime: createTime.value,
          originalPriceShow: originalPriceShow.value
        }

        if(newOrderId.value) {
          params.id = newOrderId.value
        }
        // 保存先情况在push
        // list.payMoneys = []
        let result:any = await usePromiseRequest('pay/order/completeOrder', params, 'POST')
          
            list.payMoneys.push({
              orderId: result.data.id,
              details: list.payment
            })
      }
      

    }

    // 存放收费打印数据
    const printList = ref<any[]>([])
    watch(() => printList.value, async(newV) => {
      await nextTick()
      printJS({
          printable: 'print-js',
          type: 'html',
          scanStyles: false,
          css: 'public/print.css'
        })
    })
    
    // 收费接口
    const handleArrears = () => {
      console.log(list.payMoneys, '完成')

        for(let i = 0; i < list.payMoneys.length; i++) {
          for(let j = i + 1; j < list.payMoneys.length; j++) {
            if(list.payMoneys[i].orderId == (list.payMoneys[j] && list.payMoneys[j].orderId)) {
              list.payMoneys.splice(j, 1);
              j--;
            }
          }
        }
        
        let params =  {
          customerId: personInfo.customerId,
          remark: list.remark,
          payTime: payTime.value,
          payMoneys: list.payMoneys
        }
        request.sendRequest({
            address: 'pay/order/payOrder',
            params: params,
            success: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg)
              ElMessage.success('收费' + resp.msg)
              printList.value = resp.data || []
              list.payMoneys = []
              list.payment = [
                {
                  isAdd: true, // 是否显示添加
                  payType: '', // 支付方式
                  moneyShow: '' // 实付金额
                }
              ]
              list.remark =''
              closeDialog()
              req()

            },
            fail: (resp: RespData) => {
              if(resp.code !== 0) return ElMessage.error(resp.msg)
              
            },
            method: "POST",
          })
      
      
    }

    return {
      data,
      columns,
      ...toRefs(search),
      today,
      handleGrant,
      onToDetail,
      handleChangeDate,

      handleCurrentChange,
      handleSizeChange,
      hanledSearch,
      tableHeight,

      dialogVisible,
      closeDialog,
      dialogBtnData,
      modelOptions,
      modelId,
      count,

      goChargeHistory,
      goCharge,
      handleDelItem,

      // 打印数据
      printList,

      arrearsTitle,
      dialogVisibleCharge,
      dialogChargeBtn,
      MockColumns,
      addProjectList,
      getLeftData,
      getRightData,
      getLeftBottomData,
      getRightBottomData,
      orderDetailSumMoneyShow,
      originalPriceShow,
      accountBalance,
      giftsOfGoldShow,
      totalArrears,

      paid,
      paidArrearageList,

      paidInAmount,
      paidInAMountInput,
      restMoney,
      allArrearsCopy,
      handleAccountingOrder,
      ...toRefs(list),
      ...toRefs(personInfo),

      payTime,

      handleChange,
      handleVolidateFn,
      handleChangeInputVal,
      handleChangeValue,
      optionsDoctors,
      optionsNurse,
      secondaryUserOptions,
      getDoctorAndNurse,
      del,
      paymentOptions,
      addPayment,
      delPayment,
      getCustomerDebtOrder,
      getPayMent,
      handleSelectionChange,
      newOrderId,
      saveOrder,
      handleArrears,
      male,
      female,
      getName,

      addPaymentItemList,
      delPaymentItemList,
    }
  }
})
</script>

<style lang="scss" scoped>
@import '@style/chargedialog';
.btn-text {
  font-size: $fontSize-3;
  color: #606266;
}

.none { display:none;}

.flex {
  display: flex;
  flex-direction: row;
  min-height: 80px;
  line-height: 80px;
  background-color: $a2-Color;
  box-shadow: 0 2px 10px #e9e9e9;
  border-radius: 8px;
}
.person-info {
  display: flex;
  align-items: center;
  margin: 0 20px;
  .icon {
    width: 32px;
    height: 32px;
    padding: 0 10px;
  }

  .name {
    font-size: $fontSize-2;
    font-weight: 600;
    margin-left: 20px;
  }

  .avarat {
    height: 100%;
    display: flex;
    align-items: center;
    & > span {
      margin: 2px;
      width: 40px;
      height: 40px;
    }
  }
}

.info {
  & > div {
    height: 40px;
    line-height: 40px;
  }
  // display: flex;
  // flex-direction: column;

}
</style>